package cn.bdqn.controller;

import cn.bdqn.config.shiro.MyRealm;
import cn.bdqn.pojo.Role;
import cn.bdqn.pojo.SysRight;
import cn.bdqn.pojo.User;
import cn.bdqn.service.SysRightService;
import cn.bdqn.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Resource
    UserService userService;
    @Resource
    SysRightService sysRightService;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 跳转登录页面
     *
     * @return
     */
    @RequestMapping("/login")
    public String login() {
        return "login";
    }
        /**
         * 跳转首页
         * @return
         */
        @RequestMapping("/main")
        public String main(){
            return "main";
        }
        /**
         * 登录
         * @param usrName
         * @param usrPassword
         * @param model
         * @param session
         * @return
         */
        @RequestMapping(value = "/dologin")
        public String dologin (String usrName, String usrPassword,boolean rememberMe,
                Model model, HttpSession session){
//            //调用service方法，进行用户匹配
//            User user = userService.login(usrName, usrPassword);
//            if (user != null) {//登录成功
//            //放入session
//                session.setAttribute("loginUser", user);
//            //重定向到main方法
//                return "redirect:/main";
//            } else {
//                //页面跳转（login.html）带提示信息--转发
//                model.addAttribute("msg", "用户名或密码不正确");
//                //转发到login.html
//                return "lgogin";
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token=new UsernamePasswordToken(usrName,usrPassword,rememberMe);
            try {
                subject.login(token);
                User user = (User)subject.getPrincipal();
                Role role = user.getRole();
                List<SysRight> sysRights = sysRightService.selectRoleId(role.getRoleId());
                role.getRights().addAll(sysRights);
//                放入session
                session.setAttribute("loginUser", user);
                stringRedisTemplate.delete("shiro_login_count"+token.getUsername()+token.getUsername());

                RealmSecurityManager realmSecurityManager = (RealmSecurityManager)SecurityUtils.getSecurityManager();
                MyRealm realm = (MyRealm)realmSecurityManager.getRealms().iterator().next();
                realm.clearMyCachedAuthorizationInfo();

                //重定向到main方法
                return "redirect:/main";
            } catch (AuthenticationException e) {
                //页面跳转（login.html）带提示信息--转发
                model.addAttribute("msg", "用户名或密码不正确");
                //转发到login.html
                return "login";
            }
        }

        /**
         * 退出
         * @param session
         * @return
         */
        @RequestMapping("/logout")
        public String logout (HttpSession session){
            session.removeAttribute("loginUser");
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return "login";
        }
    /**
     * 跳转403页面
     * @return
     */
    @RequestMapping("/403")
    public String authorization(){
        return "403";
    }
    }


